import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse
} from "axios";
import { Message } from "element-ui";
import store from "@/store/";
import { debugLog } from "./dev-log";
import { HTTP_OK } from "@/api/constants";

// create an axios instance
const instance: AxiosInstance = axios.create({
  baseURL: process.env.VUE_APP_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
});

// request interceptor
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    return config;
  },
  error => {
    // do something with request error
    debugLog(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
instance.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  // 协议上的错误在这里被处理了。
  // 以后不会返回 AxiosResponse, 只返回AxiosResponse.Data
  (response: AxiosResponse) => {
    console.assert(response.status === 200, "不应该是这样");
    return response.data;
  },
  (error: AxiosError) => {
    const { response } = error;
    switch (response.status) {
      case 403:
        store.dispatch("user/logout");
        break;
      default:
        Message.error(response.statusText);
    }
    return Promise.reject(error);
  }
);

export default instance;
